/**
 * 
 */
package org.xnat.xnatfs.webdav;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author blezek
 * 
 */
public class Bundle extends VirtualDirectory {
  private final static Logger logger = Logger.getLogger ( Bundle.class );

  public Bundle ( XNATFS x, String path, String name, String url ) {
    super ( x, path, name, url );
    elementURL = mURL + "files?format=json";
    childKeys.add ( "Name" );
  }

  @Override
  public VirtualResource child ( String childName ) {
    try {
      getElementList ();
    } catch ( Exception e ) {
      logger.error ( "Failed to cache children", e );
    }

    logger.debug ( "child: create " + childName );
    if ( childMap.containsKey ( childName ) ) {
      ChildEntry entry = childMap.get ( childName );
      return new RemoteFile ( xnatfs, absolutePath, childName, mURL + childURL ( childName ), entry.contentLength );
    }
    return null;
  }

  private String childURL ( String name ) {
    return "files/" + name;
  }

  // FIXME temporary work around for subfolders of the file resource that simply
  // ignores any file in a subfolder
  // http://code.google.com/p/xnatfs/issues/detail?id=11
  @Override
  protected ChildEntry getChildEntryFromJSON ( JSONObject obj ) throws JSONException {
    String fsURL = childURL ( obj.getString ( "Name" ) );
    String restURL = obj.getString ( "URI" );
    if ( restURL.endsWith ( fsURL ) ) {
      ChildEntry entry = super.getChildEntryFromJSON ( obj );
      entry.contentLength = obj.getLong ( "Size" );
      return entry;
    }
    logger.debug ( "Ignoring RemoteFile " + fsURL );
    return null;
  }
}
